package com.gzhryc.jdbc;

import com.gzhryc.jdbc.annotaion.*;
import com.gzhryc.jdbc.enums.DateBranchTableType;
import com.gzhryc.jdbc.log.Logger;
import com.gzhryc.jdbc.models.ConnectInfo;
import com.gzhryc.jdbc.models.JoinEntity;
import com.gzhryc.jdbc.models.Parameters;
import com.gzhryc.jdbc.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.*;

public class DateBranchTableDao<T> extends BaseDao<T> {

	static Logger log = Logger.getLogger(DateBranchTableDao.class);

	protected String originalTableName;
	protected DateBranchTable dateBranchTable;
	protected Date date;
	protected List<String> prevTableNames;
	protected boolean hashTableName = true;
	protected List<String> checkTableNames;

	public DateBranchTableDao(String jdbcKey, Date date) {
		super(jdbcKey);
		this.checkTableNames = new ArrayList<>();

		if(date != null) {
			this.dateBranchTable = clazz.getAnnotation(DateBranchTable.class);
			this.date = date;

			ConnectInfo info = ConnectionFactory.getConnectInfo(this.getJdbcKey());
			DbHelper helper = HelperUtils.createDbHelper(info.getKey());

			String suffix = DateBranchHelper.getTableSuffix(this.dateBranchTable.type(), this.date);
			this.originalTableName = this.tableName;
			String tempTableName = originalTableName + suffix;
			try {
				if (helper.existTable(info.getDbName(), tempTableName)) {
					this.tableName = tempTableName;
				} else {
					hashTableName = false;
					if(DateTools.isSameMonth(new Date(),date)){
						//跨表时触发
						View view = clazz.getAnnotation(View.class);
						if (view != null) {
							String asSql = view.as().replaceAll("\\{DateBranchSuffix\\}", suffix);
							DbUtils.createView(info, this.tableName, asSql);
						} else {
							DbUtils.createTable(info, clazz, this.tableName);
						}
					}else {
						log.error("{{0}}表不存在", tempTableName);
					}
				}
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			}
		}
	}

	public DateBranchTableDao(String jdbcKey, Date date, int prevNum) {
		super(jdbcKey);
		this.checkTableNames = new ArrayList<>();
		this.dateBranchTable = clazz.getAnnotation(DateBranchTable.class);
		this.date = date;

		ConnectInfo info = ConnectionFactory.getConnectInfo(this.getJdbcKey());
		DbHelper helper = HelperUtils.createDbHelper(info.getKey());

		String suffix = DateBranchHelper.getTableSuffix(this.dateBranchTable.type(), this.date);
		this.originalTableName = this.tableName;
		this.tableName = originalTableName + suffix;

		View view = clazz.getAnnotation(View.class);
		if (view != null) {
			String asSql = view.as().replaceAll("\\{DateBranchSuffix\\}", suffix);
			DbUtils.createView(info, this.tableName, asSql);
		} else {
			DbUtils.createTable(info, clazz, this.tableName);
		}

		this.prevTableNames = new ArrayList<String>();

		for (int i = 1; i <= prevNum; i++) {
			String prevTableName = getPrevTableName(originalTableName, this.date, i);
			if(StringUtils.isBlank(prevTableName)) {
				break;
			}

			try {
				if (helper.existTable(info.getDbName(), prevTableName)) {
					prevTableNames.add(prevTableName);
				} else {
					break;
				}
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			}
		}
	}

	protected void setBranchTableName(String branchTableName) {
		if (this.prevTableNames != null) {
			boolean toAdd = this.prevTableNames.size() == 0;
			if (this.prevTableNames.size() < 5) {
				toAdd = true;
			}

			if (toAdd) {
				ConnectInfo info = ConnectionFactory.getConnectInfo(this.getJdbcKey());
				DbHelper helper = HelperUtils.createDbHelper(info.getKey());
				try {
					if (helper.existTable(info.getDbName(), branchTableName)) {
						this.prevTableNames.add(branchTableName);
					}
				} catch (SQLException e) {
					log.error(e.getMessage(), e);
				}
			}
		}
	}

	protected String getPrevTableName(String originalTableName, Date currentDate, int prevNum) {
		if (DateBranchTableType.year.equals(dateBranchTable.type())) {
			Date prevDate = DateUtils.addYears(currentDate, -prevNum);
			String year = DateFormatUtils.format(prevDate, "yyyy");
			return originalTableName + "_" + year;
		} else if (DateBranchTableType.halfYear.equals(dateBranchTable.type())) {
			double temp = 0.0;
			if (prevNum >= 2) {
				temp = temp + (prevNum / 2.0);
			}
			if (prevNum % 2 > 0) {
				temp = temp + 0.5;
			}

			Calendar cale = Calendar.getInstance();
			cale.setTime(currentDate);
			int halfYear = cale.get(Calendar.MONTH) / 6 + 1;
			if (halfYear == 1) {
				temp = temp + 0.5;
			}
			Date prevDate = currentDate;
			if (temp >= 1) {
				prevDate = DateUtils.addYears(currentDate, -(int) temp);
			}
			if (temp % 1 > 0) {
				String prevYear = DateFormatUtils.format(prevDate, "yyyy");
				return originalTableName + "_" + prevYear + "01";
			} else {
				String prevYear = DateFormatUtils.format(prevDate, "yyyy");
				return originalTableName + "_" + prevYear + "02";
			}
		} else if (DateBranchTableType.quarter.equals(dateBranchTable.type())) {
			Calendar cale = Calendar.getInstance();
			cale.setTime(currentDate);
			int quarter = cale.get(Calendar.MONTH) / 3 + 1;
			int temp = 0;
			int temp1 = prevNum;
			if (prevNum - quarter >= 0) {
				temp = (prevNum - quarter) / 4 + 1;
				temp1 = (prevNum - quarter) % 4;
			}

			Date prevDate = currentDate;
			if (temp >= 1) {
				prevDate = DateUtils.addYears(currentDate, -temp);
			}
			String prevYear = DateFormatUtils.format(prevDate, "yyyy");
			return originalTableName + "_" + prevYear + "0" + (4 - temp1);
		} else if (DateBranchTableType.month.equals(dateBranchTable.type())) {
			Date prevDate = DateUtils.addMonths(currentDate, -prevNum);
			String month = DateFormatUtils.format(prevDate, "yyyyMM");
			return originalTableName + "_" + month;
		}
		return null;
	}

	public void tryRefresh() {
		this.tryRefresh(new Date());
	}

	public void tryRefresh(Date currentDate) {
		if (!DateTools.isSameMonth(this.date, currentDate)) {
			String suffix = DateBranchHelper.getTableSuffix(this.dateBranchTable.type(), this.date);
			String newTableName = this.originalTableName + suffix;
			if (!newTableName.equals(this.tableName)) {
				if (this.prevTableNames != null) {
					this.prevTableNames.add(0, this.tableName);
				}
				this.tableName = newTableName;
				if(!checkTableNames.contains(tableName)) {
					ConnectInfo info = ConnectionFactory.getConnectInfo(this.getJdbcKey());
					View view = clazz.getAnnotation(View.class);
					if (view != null) {
						String asSql = view.as().replaceAll("\\{DateBranchSuffix\\}", suffix);
						DbUtils.createView(info, this.tableName, asSql);
					} else {
						DbUtils.createTable(info, clazz, this.tableName);
					}
					checkTableNames.add(tableName);
				}
			}
		}
	}

	public boolean hasTableName(){
		return hashTableName;
	}

	public T getBranch(Conditions condition) throws SQLException {
		List<Field> fields = EntityUtils.findTableColumn(this.clazz);
		StringBuilder fieldStr = new StringBuilder();
		if (this.idField != null) {
			Column column = idField.getAnnotation(Column.class);
			String name = idField.getName();
			if (column != null && StringUtils.isNotBlank(column.name())) {
				name = column.name();
			}
			fieldStr.append(name);
		}
		for (int i = 0; i < fields.size(); i++) {
			Field field = fields.get(i);
			Column column = field.getAnnotation(Column.class);
			if (column != null) {
				if (idField != null && field.getName().equals(idField.getName())) {
					continue;
				}
				String name = column.name();
				if (StringUtils.isBlank(name)) {
					name = field.getName();
				}
				if (fieldStr.length() == 0) {
					fieldStr.append(name);
				} else {
					fieldStr.append(",").append(name);
				}
			}
		}

		Query query = new Query();
		String str = condition.toSql(query.getParams(), true);

		query.setSql("SELECT " + fieldStr.toString() + " FROM " + tableName + str);
		T obj = this.jdbcHelper.get(query, clazz);

		if (obj == null && this.prevTableNames != null && this.prevTableNames.size() > 0) {
			for (String branchTableName : this.prevTableNames) {
				query.setSql("SELECT " + fieldStr.toString() + " FROM " + branchTableName + str);
				obj = this.jdbcHelper.get(query, clazz);
				if (obj != null) {
					break;
				}
			}
		}
		return obj;
	}

	public T getBranchJoin(Conditions condition) throws SQLException {
		String[] temp = buildJoinSql();
		Query query = new Query();
		String str = condition.toSql(query.getParams(), "t", true);

		query.setSql("SELECT " + temp[0] + " FROM " + tableName + " t " + temp[1] + str);
		T obj = this.jdbcHelper.getJoin(query, clazz);

		if (obj == null && this.prevTableNames != null && this.prevTableNames.size() > 0) {
			for (String branchTableName : this.prevTableNames) {
				query.setSql("SELECT " + temp[0] + " FROM " + branchTableName + " t" + temp[1] + str);
				obj = this.jdbcHelper.getJoin(query, clazz);
				if (obj != null) {
					break;
				}
			}
		}
		return obj;
	}

	public T getBranchById(Object id) throws SQLException {
		if (id != null && this.idField != null) {
			String idName = EntityUtils.getName(idField);
			List<Field> fields = EntityUtils.findTableColumn(this.clazz);
			StringBuilder fieldStr = new StringBuilder();
			if (idField != null) {
				Column column = idField.getAnnotation(Column.class);
				String name = idField.getName();
				if (column != null && StringUtils.isNotBlank(column.name())) {
					name = column.name();
				}
				fieldStr.append(name);
			}
			for (int i = 0; i < fields.size(); i++) {
				Field field = fields.get(i);
				Column column = field.getAnnotation(Column.class);
				if (column != null) {
					if (idField != null && field.getName().equals(idField.getName())) {
						continue;
					}
					String name = column.name();
					if (StringUtils.isBlank(name)) {
						name = field.getName();
					}
					if (fieldStr.length() == 0) {
						fieldStr.append(name);
					} else {
						fieldStr.append(",").append(name);
					}
				}
			}

			Query query = new Query("SELECT " + fieldStr.toString() + " FROM " + tableName + " WHERE " + idName + "=?");
			query.getParams().setObject(id);
			T obj = this.jdbcHelper.get(query, clazz);

			if (obj == null && this.prevTableNames != null && this.prevTableNames.size() > 0) {
				for (String branchTableName : this.prevTableNames) {
					query.setSql("SELECT " + fieldStr.toString() + " FROM " + branchTableName + " WHERE " + idName + "=?");
					obj = this.jdbcHelper.get(query, clazz);
					if (obj != null) {
						break;
					}
				}
			}
			return obj;
		} else {
			throw new SQLException("id is null");
		}
	}

	public T getBranchJoinById(Object id) throws SQLException {
		if (id != null && idField != null) {
			String idName = EntityUtils.getName(idField);
			String[] temp = buildJoinSql();
			String sql = "SELECT " + temp[0] + " FROM " + tableName + " t" + temp[1] + " WHERE t." + idName + "=?";
			Query query = new Query(sql);
			query.getParams().setObject(id);
			T obj = this.jdbcHelper.getJoin(query, clazz);

			if (obj == null && this.prevTableNames != null && this.prevTableNames.size() > 0) {
				for (String branchTableName : this.prevTableNames) {
					query.setSql("SELECT " + temp[0] + " FROM " + branchTableName + " t" + temp[1] + " WHERE t." + idName + "=?");
					obj = this.jdbcHelper.getJoin(query, clazz);
					if (obj != null) {
						break;
					}
				}
			}
			return obj;
		} else {
			throw new SQLException("id is null");
		}
	}

	public int updateBranchNotNull(T obj) throws SQLException {
		try {
			if (idField == null) {
				return 0;
			}
			Object idVal = idField.get(obj);
			if (idVal == null) {
				return 0;
			}
			Parameters params = new Parameters();
			List<Field> fields = EntityUtils.findTableColumn(obj.getClass());
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < fields.size(); i++) {
				Field field = fields.get(i);
				if (field.getName().equals(idField.getName())) {
					continue;
				}
				Object value = field.get(obj);
				if (value != null) {
					String name = EntityUtils.getName(field);
					sb.append(",").append(name).append("=?");
					params.setField(field, value);
				}
			}

			if (sb.length() > 1) {
				String fieldStr = sb.substring(1);
				String name = EntityUtils.getName(idField);
				String sql = "update " + tableName + " set " + fieldStr + " where " + name + "=?";
				params.setField(idField, idVal);
				int result = jdbcHelper.update(sql, params);

				if (result <= 0 && this.prevTableNames != null && this.prevTableNames.size() > 0) {
					for (String branchTableName : this.prevTableNames) {
						sql = "update " + branchTableName + " set " + fieldStr + " where " + name + "=?";
						result = jdbcHelper.update(sql, params);
						if (result > 0) {
							break;
						}
					}
				}
				return result;
			}
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new SQLException(e.fillInStackTrace());
		}
		return 0;
	}

	public int updateBranchNotNull(T obj, Conditions condition) throws SQLException {
		try {
			Parameters params = new Parameters();
			List<Field> fields = EntityUtils.findTableColumn(obj.getClass());

			StringBuilder fieldStr = new StringBuilder();
			for (int i = 0; i < fields.size(); i++) {
				Field field = fields.get(i);
				if (idField != null && field.getName().equals(idField.getName())) {
					Id id = idField.getAnnotation(Id.class); // 如果自动生成则不进行修改
					if (id.auto()) {
						continue;
					}
				}
				Object value = field.get(obj);
				if (value != null) {
					String name = EntityUtils.getName(field);
					fieldStr.append(",").append(name).append("=?");
					params.setField(field, value);
				}
			}

			String temp = fieldStr.substring(1);
			String str = condition.toSql(params, true);

			StringBuilder sql = new StringBuilder("update " + tableName + " set ");
			sql.append(temp);
			sql.append(str);
			int result = this.jdbcHelper.update(sql.toString(), params);
			if (result > 0) {
				return result;
			} else if (this.prevTableNames != null && this.prevTableNames.size() > 0) {
				for (String branchTableName : this.prevTableNames) {
					sql = new StringBuilder("update " + branchTableName + " set ");
					sql.append(temp);
					sql.append(str);
					result = this.jdbcHelper.update(sql.toString(), params);
					if (result > 0) {
						break;
					}
				}
			}
			return result;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new SQLException(e.fillInStackTrace());
		}
	}

	public int updateBranch(Map<String, Object> data, Conditions condition) throws SQLException {
		try {
			Parameters params = new Parameters();
			List<Field> fields = EntityUtils.findTableColumn(clazz);
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < fields.size(); i++) {
				Field field = fields.get(i);
				// 只支持Column注释的属性
				if (field.isAnnotationPresent(Column.class)) {
					if (idField != null && field.getName().equals(idField.getName())) {
						continue;
					}
					// 检查是否存在
					if (data.containsKey(field.getName())) {
						Object value = data.get(field.getName());
						String name = EntityUtils.getName(field);
						if (value != null) {
							sb.append(",").append(name).append("= ?");
							params.setField(field, value);
						} else {
							sb.append(",").append(name).append("= null");
						}
					}
				}
			}
			String fieldStr = sb.substring(1);
			String str = condition.toSql(params, true);
			String sql = "UPDATE " + tableName + " SET " + fieldStr + str;
			int result = jdbcHelper.update(sql, params);

			if (result <= 0 && this.prevTableNames != null && this.prevTableNames.size() > 0) {
				for (String branchTableName : this.prevTableNames) {
					sql = "UPDATE " + branchTableName + " SET " + fieldStr + str;
					result = jdbcHelper.update(sql, params);
					if (result > 0) {
						break;
					}
				}
			}
			return result;
		} catch (IllegalArgumentException e) {
			throw new SQLException(e.fillInStackTrace());
		}
	}

	/**
	 * 根据ID删除数据
	 *
	 * @param id
	 * @return
	 * @throws SQLException
	 */
	public int deleteBranchById(Object id) throws SQLException {
		if (idField != null) {
			Parameters params = new Parameters();
			String idName = EntityUtils.getName(idField);
			String sql = "delete from " + tableName + " where " + idName + "=?";
			params.setField(idField, id);
			int result = jdbcHelper.update(sql, params);

			if (result <= 0 && this.prevTableNames != null && this.prevTableNames.size() > 0) {
				for (String branchTableName : this.prevTableNames) {
					sql = "delete from " + branchTableName + " where " + idName + "=?";
					result = jdbcHelper.update(sql, params);
					if (result > 0) {
						break;
					}
				}
			}
			return result;
		} else {
			throw new SQLException("is not table entity");
		}
	}

	/**
	 * 根据条件删除
	 *
	 * @param condition
	 * @return
	 * @throws SQLException
	 */
	public int deleteBranchByCondition(Conditions condition) throws SQLException {
		Parameters params = new Parameters();
		String str = condition.toSql(params, true);
		StringBuilder sql = new StringBuilder("delete from " + tableName);
		sql.append(str);
		int result = jdbcHelper.update(sql.toString(), params);
		if (result <= 0 && this.prevTableNames != null && this.prevTableNames.size() > 0) {
			for (String branchTableName : this.prevTableNames) {
				sql = new StringBuilder("delete from " + branchTableName);
				sql.append(str);
				result = jdbcHelper.update(sql.toString(), params);
				if (result > 0) {
					break;
				}
			}
		}
		return result;
	}

	public Date getPrevDate() {
		Date currentDate = new Date();
		if (DateBranchTableType.year.equals(dateBranchTable.type())) {
			Date prevDate = DateUtils.addYears(currentDate, -1);
			return prevDate;
		} else if (DateBranchTableType.halfYear.equals(dateBranchTable.type())) {
			Calendar cale = Calendar.getInstance();
			cale.setTime(currentDate);
			int halfYear = cale.get(Calendar.MONTH) / 6 + 1;
			if (halfYear == 1) {
				cale.add(Calendar.YEAR, -1);
				cale.set(Calendar.MONTH, 7);
			} else {
				cale.set(Calendar.MONTH, 1);
				return cale.getTime();
			}
			return cale.getTime();
		} else if (DateBranchTableType.quarter.equals(dateBranchTable.type())) {
			Calendar cale = Calendar.getInstance();
			cale.setTime(currentDate);
			int quarter = cale.get(Calendar.MONTH) / 3 + 1;
			if (quarter == 1) {
				cale.add(Calendar.YEAR, -1);
				cale.set(Calendar.MONTH, 10);
			} else if (quarter == 2) {
				cale.set(Calendar.MONTH, 1);
				return cale.getTime();
			} else if (quarter == 3) {
				cale.set(Calendar.MONTH, 4);
				return cale.getTime();
			} else if (quarter == 4) {
				cale.set(Calendar.MONTH, 7);
				return cale.getTime();
			}
			return cale.getTime();
		} else if (DateBranchTableType.month.equals(dateBranchTable.type())) {
			Date prevDate = DateUtils.addMonths(currentDate, -1);
			return prevDate;
		}
		return null;
	}

	/**
	 * 解析表连接对象
	 */
	protected void analysisJoin() {
		Field[] fields = ClassTools.getDeclaredFields(this.clazz);
		for (Field field : fields) {
			Join join = field.getAnnotation(Join.class);
			if (join != null) {
				if (joinClassList == null) {
					joinClassList = new ArrayList<JoinEntity>();
				}
				String tableName = join.toTable();
				if (StringUtils.isBlank(tableName)) {
					tableName = EntityUtils.getTableName(field.getType());
				}
				JoinEntity joinEntity = new JoinEntity();
				joinEntity.setFieldName(field.getName());
				joinEntity.setFromField(join.fromField());
				joinEntity.setType(join.type().toUpperCase());
				joinEntity.setClazz(field.getType());
				joinEntity.setToTable(tableName);
				joinEntity.setToField(join.toField());
				joinEntity.setToTableAlias(field.getName());
				joinEntity.setPriority(join.priority());
				DateBranchJoin dateBranchJoin = field.getAnnotation(DateBranchJoin.class);
				if (dateBranchJoin != null) {
					joinEntity.setIsDateBranch(true);
				}
				joinClassList.add(joinEntity);
			} else {
				JoinField joinField = field.getAnnotation(JoinField.class);
				if (joinField != null) {
					if (joinClassList == null) {
						joinClassList = new ArrayList<JoinEntity>();
					}
					String tableName = joinField.toTable();
					if (StringUtils.isNotBlank(tableName)) {
						JoinEntity joinEntity = new JoinEntity();
						joinEntity.setFieldName(field.getName());
						joinEntity.setName(joinField.name());
						joinEntity.setFromField(joinField.fromField());
						joinEntity.setType(joinField.type().toUpperCase());
						joinEntity.setClazz(this.clazz);
						joinEntity.setToTable(tableName);
						joinEntity.setToField(joinField.toField());
						joinEntity.setToTableAlias(joinField.toTableAlias());
						if (StringUtils.isBlank(joinEntity.getToTableAlias())) {
							joinEntity.setToTableAlias(tableName);
						}
						joinEntity.setPriority(joinField.priority());
						DateBranchJoin dateBranchJoin = field.getAnnotation(DateBranchJoin.class);
						if (dateBranchJoin != null) {
							joinEntity.setIsDateBranch(true);
						}
						joinClassList.add(joinEntity);
					}
				} else {
					Parent parent = field.getAnnotation(Parent.class);
					if (parent != null) {
						if (joinClassList == null) {
							joinClassList = new ArrayList<JoinEntity>();
						}
						JoinEntity joinEntity = new JoinEntity();
						joinEntity.setFieldName(field.getName());
						joinEntity.setName(parent.value());
						joinEntity.setFromField(new String[] { "parent_id" });
						joinEntity.setType("LEFT");
						joinEntity.setClazz(this.clazz);
						joinEntity.setToTable(tableName);
						joinEntity.setToField(new String[] { idField.getName() });
						joinEntity.setToTableAlias("parent");
						joinClassList.add(joinEntity);
					}
				}
			}
		}
		if (joinClassList != null && joinClassList.size() > 1) {
			Collections.sort(joinClassList);
		}
	}

	protected String[] buildJoinSql() {
		List<Field> fields = EntityUtils.findTableColumn(this.clazz);
		StringBuilder sb = new StringBuilder("");
		if (this.idField != null) {
			Column column = idField.getAnnotation(Column.class);
			String name = idField.getName();
			if (column != null && StringUtils.isNotBlank(column.name())) {
				name = column.name();
			}
			sb.append("t.").append(name);
		}
		for (int i = 0; i < fields.size(); i++) {
			Field field = fields.get(i);
			Column column = field.getAnnotation(Column.class);
			if (column != null) {
				if (idField != null && field.getName().equals(idField.getName())) {
					continue;
				}
				String name = column.name();
				if (StringUtils.isBlank(name)) {
					name = field.getName();
				}
				if (sb.length() == 0) {
					sb.append("t.").append(name);
				} else {
					sb.append(",t.").append(name);
				}
			}
		}
		String sql = "";
		if (this.joinClassList != null) {
			ConnectInfo info = ConnectionFactory.getConnectInfo(this.getJdbcKey());
			DbHelper helper = HelperUtils.createDbHelper(info.getKey());
			// 处理多个相同表连接
			List<String> aliasList = new ArrayList<String>();
			for (JoinEntity joinEntity : this.joinClassList) {
				String alias = joinEntity.getToTableAlias();

				if (StringUtils.isNotBlank(joinEntity.getName())) {
					sb.append(",").append(alias).append(".").append(joinEntity.getName()).append(" AS ").append(joinEntity.getFieldName());
				} else {
					List<Field> childFields = EntityUtils.findTableColumn(joinEntity.getClazz());
					for (int i = 0; i < childFields.size(); i++) {
						Field field = childFields.get(i);
						Column column = field.getAnnotation(Column.class);
						if (column != null) {
							String name = column.name();
							if (StringUtils.isBlank(name)) {
								name = field.getName();
							}
							sb.append(",").append(alias).append(".").append(name);
						} else {
							Id id = field.getAnnotation(Id.class);
							if (id != null) {
								sb.append(",").append(alias).append(".").append(field.getName());
							}
						}
					}
				}
				// 相同的表连接只能一次
				if (aliasList.contains(alias)) {
					continue;
				}
				String fromFieldAlias = "t.";
				if (joinEntity.getFromField()[0].contains(".")) {
					fromFieldAlias = "";
				}
				String toTableName = joinEntity.getToTable();
				if (joinEntity.getIsDateBranch() && this.date != null) {
					String tempTableName = toTableName + DateBranchHelper.getTableSuffix(this.dateBranchTable.type(), this.date);
					try {
						assert helper != null;
						if (helper.existTable(info.getDbName(), tempTableName)) {
							toTableName = tempTableName;
						}
					} catch (SQLException e) {
						log.error(e.getMessage(), e);
					}
				}
				String temp = joinEntity.getType() + " JOIN " + toTableName + " " + alias + " ON " + alias + "." + joinEntity.getToField()[0] + " = "
						+ fromFieldAlias + joinEntity.getFromField()[0];
				for (int i = 1; i < joinEntity.getFromField().length && i < joinEntity.getToField().length; i++) {
					fromFieldAlias = "t.";
					if (joinEntity.getFromField()[i].contains(".")) {
						fromFieldAlias = "";
					}
					temp = temp + " AND " + alias + "." + joinEntity.getToField()[i] + " = " + fromFieldAlias + joinEntity.getFromField()[i];
				}
				sql = sql + " " + temp;
				aliasList.add(alias);
			}
		}
		return new String[] { sb.toString(), sql };
	}

	public Date getDate(){
		return date;
	}
}
